import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, Image, Popconfirm, message, Modal, Dropdown, Progress } from 'antd';
import { PlusOutlined, ExportOutlined, ImportOutlined, MoreOutlined, EditOutlined, DeleteOutlined, EyeOutlined, CopyOutlined, SettingOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { getCourseList, deleteCourse, copyCourse, updateCourseStatus, exportCourses } from '@/services/courseManagementApi';
import CourseForm from './components/CourseForm';
import CourseDetail from './components/CourseDetail';
import LessonManagement from './components/LessonManagement';

const CourseList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [courseFormVisible, setCourseFormVisible] = useState(false);
  const [courseDetailVisible, setCourseDetailVisible] = useState(false);
  const [lessonManagementVisible, setLessonManagementVisible] = useState(false);
  const [currentCourse, setCurrentCourse] = useState<COURSE.CourseModel | undefined>();
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');

  // 课程状态标签颜色映射
  const statusColorMap = {
    draft: 'default',
    published: 'green',
    archived: 'orange',
  };

  // 难度等级标签颜色映射
  const difficultyColorMap = {
    beginner: 'green',
    intermediate: 'orange',
    advanced: 'red',
  };

  // 表格列定义
  const columns: ProColumns<COURSE.CourseModel>[] = [
    {
      title: '课程ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '封面',
      dataIndex: 'cover',
      width: 100,
      search: false,
      render: (_, record) => (
        <Image
          src={record.cover}
          alt={record.title}
          width={60}
          height={40}
          style={{ objectFit: 'cover', borderRadius: 4 }}
          fallback=""
        />
      ),
    },
    {
      title: '课程标题',
      dataIndex: 'title',
      width: 200,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '分类',
      dataIndex: 'category_name',
      width: 120,
      search: false,
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      width: 100,
      valueType: 'select',
      valueEnum: {
        beginner: { text: '初级', status: 'Success' },
        intermediate: { text: '中级', status: 'Warning' },
        advanced: { text: '高级', status: 'Error' },
      },
      render: (_, record) => (
        <Tag color={difficultyColorMap[record.difficulty]}>
          {record.difficulty === 'beginner' ? '初级' : record.difficulty === 'intermediate' ? '中级' : '高级'}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      valueType: 'select',
      valueEnum: {
        draft: { text: '草稿', status: 'Default' },
        published: { text: '已发布', status: 'Success' },
        archived: { text: '已归档', status: 'Warning' },
      },
      render: (_, record) => (
        <Tag color={statusColorMap[record.status]}>
          {record.status === 'draft' ? '草稿' : record.status === 'published' ? '已发布' : '已归档'}
        </Tag>
      ),
    },
    {
      title: '课时数',
      dataIndex: 'lesson_count',
      width: 80,
      search: false,
    },
    {
      title: '学习人数',
      dataIndex: 'student_count',
      width: 100,
      search: false,
      render: (text) => text?.toLocaleString(),
    },
    {
      title: '完成率',
      dataIndex: 'completion_rate',
      width: 120,
      search: false,
      render: (rate) => (
        <Progress
          percent={Math.round(rate * 100)}
          size="small"
          status={rate > 0.8 ? 'success' : rate > 0.5 ? 'normal' : 'exception'}
        />
      ),
    },
    {
      title: '评分',
      dataIndex: 'rating',
      width: 80,
      search: false,
      render: (rating) => {
        const numRating = Number(rating);
        return (rating && !isNaN(numRating)) ? `${numRating.toFixed(1)}⭐` : '-';
      },
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: 100,
      search: false,
      render: (price) => {
        const numPrice = Number(price);
        return (price && !isNaN(numPrice) && numPrice > 0) ? `¥${numPrice}` : '免费';
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          onClick={() => handleViewDetail(record)}
        >
          详情
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'edit',
                label: '编辑',
                icon: <EditOutlined />,
                onClick: () => handleEdit(record),
              },
              {
                key: 'lessons',
                label: '课时管理',
                icon: <SettingOutlined />,
                onClick: () => handleLessonManagement(record),
              },
              {
                key: 'copy',
                label: '复制',
                icon: <CopyOutlined />,
                onClick: () => handleCopy(record),
              },
              {
                key: 'status',
                label: record.status === 'published' ? '下架' : '发布',
                onClick: () => handleStatusChange(record),
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 处理查看详情
  const handleViewDetail = (record: COURSE.CourseModel) => {
    setCurrentCourse(record);
    setCourseDetailVisible(true);
  };

  // 处理课时管理
  const handleLessonManagement = (record: COURSE.CourseModel) => {
    setCurrentCourse(record);
    setLessonManagementVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: COURSE.CourseModel) => {
    setCurrentCourse(record);
    setEditMode('edit');
    setCourseFormVisible(true);
  };

  // 处理复制
  const handleCopy = async (record: COURSE.CourseModel) => {
    try {
      await copyCourse(record.id, `${record.title} - 副本`);
      message.success('课程复制成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('课程复制失败');
    }
  };

  // 处理状态变更
  const handleStatusChange = (record: COURSE.CourseModel) => {
    const newStatus = record.status === 'published' ? 'archived' : 'published';
    const actionText = newStatus === 'published' ? '发布' : '下架';
    
    Modal.confirm({
      title: `确认${actionText}`,
      content: `确定要${actionText}课程 "${record.title}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await updateCourseStatus(record.id, newStatus);
          message.success(`课程${actionText}成功`);
          actionRef.current?.reload();
        } catch (error) {
          message.error(`课程${actionText}失败`);
        }
      },
    });
  };

  // 处理删除
  const handleDelete = (record: COURSE.CourseModel) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除课程 "${record.title}" 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteCourse(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理新建
  const handleCreate = () => {
    setCurrentCourse(undefined);
    setEditMode('create');
    setCourseFormVisible(true);
  };

  // 处理导出
  const handleExport = async () => {
    try {
      const blob = await exportCourses({ format: 'excel' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `课程列表_${new Date().toISOString().split('T')[0]}.xlsx`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  return (
    <PageContainer>
      <ProTable<COURSE.CourseModel>
        headerTitle="课程列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建课程
          </Button>,
          <Button
            key="export"
            icon={<ExportOutlined />}
            onClick={handleExport}
          >
            导出
          </Button>,
        ]}
        request={async (params, sort) => {
          const response = await getCourseList({
            page: params.current,
            limit: params.pageSize,
            title: params.title,
            difficulty: params.difficulty,
            status: params.status,
            category_id: params.category_id,
          });
          return {
            data: response.data.list,
            success: response.code === 200,
            total: response.data.pagination.total,
          };
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        scroll={{ x: 1600 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 课程表单弹窗 */}
      <CourseForm
        visible={courseFormVisible}
        mode={editMode}
        initialValues={currentCourse}
        onCancel={() => setCourseFormVisible(false)}
        onSuccess={() => {
          setCourseFormVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 课程详情弹窗 */}
      <CourseDetail
        visible={courseDetailVisible}
        course={currentCourse}
        onCancel={() => setCourseDetailVisible(false)}
      />

      {/* 课时管理弹窗 */}
      <LessonManagement
        visible={lessonManagementVisible}
        course={currentCourse}
        onCancel={() => setLessonManagementVisible(false)}
      />
    </PageContainer>
  );
};

export default CourseList;
